<?php
/**
 * 根据表生成CURD操作、HTML
 * User: 1874
 * Date: 2019/12/9
 * Time: 10:00
 */

namespace app\adminplatform\controller;

use app\adminplatform\model\AuthGroup;
use app\adminplatform\model\AuthRule;
use think\facade\Config;
use think\facade\Db;
use think\facade\Session;
use think\facade\View;

class Create extends Initial {
    const FORM_TEXT = 1;        //文本
    const FORM_SELECT = 2;      //下拉框
    const FORM_CHECKBOX = 3;    //复选框
    const FORM_RADIO = 4;       //单选
    const FORM_TEXTAREA = 5;    //文本域
    const OPERATE_ADD = "Operate/operate/add";          //新增路由地址
    const OPERATE_ADD_ADDRESS = "Operateoperateadd";    //新增权限地址
    const OPERATE_EDIT = "Operate/operate/edit";        //修改路由地址
    const OPERATE_EDIT_ADDRESS = "Operateoperateedit";  //修改权限地址
    private static $path;               //当前文件路径
    private static $tableName;          //要创建的表名
    private static $prefixTableName;    //去掉前缀的表名
    private static $className;          //要创建的类名
    private static $chineseClassName;   //要创建的类中文名
    private static $lowerClassName;     //首字母小写类名
    private static $primayKey;          //表主键字段
    private static $authPid;            //权限表父id
    private $output;                    //输出信息
    /*
     * 构造方法
     */
    public function initialize(){
        parent::initialize();
        //当前文件路径
        self::$path = dirname(__FILE__);
        self::$authPid = 0;
    }
    /*
     * 场景CURD页面
     */
    public function index(){
        //加载所有表数据
        $info = Db::query("SHOW TABLE STATUS");
        View::assign('info', $info);
        return View::fetch('index');
    }
    /*
     * 表字段信息
     */
    public function table(){
        $table = input("table");
        //查询表是否存在
        $exist = Db::query("show tables like '{$table}'");
        if(!$exist) alertDemo("数据表不存在");
        //查询所有字段
        $info = $this->getFieldName($table);
        //检查是否有权限
        $check = AuthGroup::checkMethod(Session::get('userData'), 'Create/createCurd');

        View::assign('info', $info);
        View::assign('check', $check);
        return View::fetch('table');
    }
    /*
     * 根据表名创建CURD控制器、方法、Html
     * @param string tableName 表名
     * @param string listFiled 列表需要字段
     * @param string addFiled 新增需要字段
     * @param string editFiled 标记需要字段
     */
    public function createCurd(){
        //获取数据
        $param = input();
        //获取要创建的表名
        self::$tableName = $tableName = $param['tableName'];
        self::$chineseClassName = $param['cnTableName'];
        //获取数据库配置表名前缀
        $prefix = Config::get("database.connections.mysql.prefix");
        //表名去掉前缀，如：tb_user_info => user_info
        self::$prefixTableName = str_replace($prefix, false, $tableName);
        //要创建的模型名转换为大驼峰命名 user_info => UserInfo
        self::$className = camelize(self::$prefixTableName);
        //首字母小写类名 user_info => userInfo
        self::$lowerClassName = lcfirst(self::$className);
        //判断表是否存在
        if($tableName){
            //查询表是否存在
            $exist = Db::query("show tables like '{$tableName}'");
            if($exist){
                //获取表的字段名
                $fields = $this->getFieldName($tableName);
                //获取表主键字段
                self::$primayKey = $this->getPrimaryKey($fields);
                if(!empty($param["features"])){
                    /** 生成model文件 */
                    $this->createModel($param);
                    /** 生成类文件 */
                    $this->createClass($fields, $param);
                    /** 生成html文件 */
                    $this->createHtml($fields, $param);
                }else{
                    $this->output .= "请勾选需要创建的功能\n";
                }
                exit(setJsonStr($this->output));
            }else{
                exit(setJsonStr('数据表不存在'));
            }
        }else{
            exit(setJsonStr('参数错误'));
        }
    }
    /*
     * 获取表的字段名
     * @param string $tableName 表名
     */
    protected function getFieldName(string $tableName): array {
        //获取表的字段名详细信息
        $fields = Db::query("show full columns from {$tableName}");
        return $fields;
    }
    /*
     * 获取主键
     * @param array $field 表字段
     */
    protected function getPrimaryKey(array $field): array {
        $info = array_filter($field, function($v){
            if($v["Key"] == "PRI") return $v;
        });
        if(empty($info)) $info[0] = $field[0];
        return $info[0];
    }
//========================================================【创建model类】=================================================
    /*
     * 生成model文件
     * @param array $createData 创建需要的字段数据
     */
    protected function createModel($createData){
        //要model的类名
        $className = self::$className;
        //类头部
        $info = "<?php \n";
        $info .= "\nnamespace app\adminplatform\model; \n";
        $info .= "use think\\facade\\Request; \n";
        $info .= "use think\\Model; \n";
        $info .= "\nclass {$className} extends Model{ \n";
        //创建模型列表方法
        if(!empty($createData["features"]["list"])){
            $info .= $this->createModelSelect(); //获取模型查询结尾前对象
            $info .= $this->createModelPage();   //获取分页方法
            $info .= $this->createModelList();   //获取列表方法
        }
        if(!empty($createData["features"][REQUEST_EDIT]) || !empty($createData["features"][REQUEST_ADD])){
            $info .= $this->createModelDetail();
        }
        $info .= "\n}";
        //模型文件路径
        $classPath = self::$path.'/../model/'.$className.'.php';
        //不存在则创建文件
        if(!file_exists($classPath)){
            //创建类文件
            $res = file_put_contents($classPath, $info);
            if($res){
                $this->output .= $className.".php 模型创建成功\n";
            }else{
                $this->output .= $className.".php 模型创建失败\n";
            }
        }else{
            exit(setJsonStr($className.".php 模型文件已存在"));
        }

    }
    /*
     * 模型查询结尾前对象
     */
    protected function createModelSelect(){
        $className = self::$className; //完整类名=model名
        $chineseClassName = self::$chineseClassName; //类的中文别名
        //创建html
        $info = "    /**\n";
        $info .= "     * 获取{$chineseClassName}查询前对象\n";
        $info .= "     */";
        $info .= "\n    public static function {$className}Model(array $"."map=[]){";
        $info .= "\n        return {$className}::where($"."map);";
        $info .= "\n    }\n";

        return $info;
    }
    /*
     * 模型列表分页方法
     */
    protected function createModelPage(){
        $className = self::$className; //完整类名=model名
        $chineseClassName = self::$chineseClassName; //类的中文别名
        //创建html
        $info = "    /**\n";
        $info .= "     * 获取{$chineseClassName}分页\n";
        $info .= "     */";
        $info .= "\n    public static function get{$className}Page(array $"."map=[]){";
        $info .= "\n        return self::{$className}Model($"."map)->paginate(['list_rows'=>PageNum,'query'=>Request::param()]);";
        $info .= "\n    }\n";

        return $info;
    }
    /*
     * 模型列表方法
     */
    protected function createModelList(){
        $className = self::$className; //完整类名=model名
        $chineseClassName = self::$chineseClassName; //类的中文别名
        //创建html
        $info = "    /**\n";
        $info .= "     * 获取{$chineseClassName}列表\n";
        $info .= "     */";
        $info .= "\n    public static function get{$className}List(array $"."map=[]){";
        $info .= "\n        return self::{$className}Model($"."map)->select();";
        $info .= "\n    }\n";

        return $info;
    }
    /*
     * 模型查询单条数据方法
     */
    protected function createModelDetail(){
        $className = self::$className; //完整类名=model名
        $chineseClassName = self::$chineseClassName; //类的中文别名
        //创建html
        $info = "    /**\n";
        $info .= "     * 获取{$chineseClassName}详情\n";
        $info .= "     */";
        $info .= "\n    public static function get{$className}Detail(array $"."map=[]){";
        $info .= "\n        return self::{$className}Model($"."map)->find();";
        $info .= "\n    }\n";

        return $info;
    }
//========================================================【创建PHP类】=================================================
    /*
     * 生成类文件
     * @param string $fields 表字段信息
     * @param array $createData 创建需要的字段数据
     */
    protected function createClass(array $fields, array $createData){
        //主键字段
        $primaryKey = self::$primayKey;
        //要创建的类名
        $className = self::$className;
        //类头部
        $info = "<?php \n";
        $info .= "\nnamespace app\adminplatform\controller; \n";
        $info .= "use app\\adminplatform\\model\\{$className} as {$className}Model; \n";
        $info .= "use app\\adminplatform\\model\\AuthGroup; \n";
        $info .= "use app\\adminplatform\\model\\Log; \n";
        $info .= "use think\\facade\Request; \n";
        $info .= "use think\\facade\View; \n";
        $info .= "use think\\facade\Session; \n";
        $info .= "\nclass {$className} extends Initial{ \n";

        //生成列表方法
        if(!empty($createData["features"][REQUEST_LIST])){
            $info .= $this->createList(self::$lowerClassName);
        }
        //生成新增/编辑统一操作入口
        if(!empty($createData["features"][REQUEST_ADD]) || !empty($createData["features"][REQUEST_EDIT])) {
            $info .= $this->createOperate(self::$lowerClassName, $primaryKey['Field']);
        }
        //生成新增方法
        if(!empty($createData["features"][REQUEST_ADD])){
            $info .= $this->createAdd(self::$lowerClassName);
        }
        //生成编辑方法
        if(!empty($createData["features"][REQUEST_EDIT])) {
            $info .= $this->createEdit(self::$lowerClassName, $primaryKey['Field']);
        }
        //生成删除方法
        if(!empty($createData["features"][REQUEST_DEL])) {
            $info .= $this->createDel(self::$lowerClassName, $primaryKey['Field']);
        }
		//生成批量删除方法
        if(!empty($createData["features"][REQUEST_DEL_ALL])) {
            $info .= $this->createDelAll(self::$lowerClassName, $primaryKey['Field']);
        }
		//生成导出方法
        if(!empty($createData["features"][REQUEST_EXPORT])) {
            $info .= $this->createExport(self::$lowerClassName, $fields, $createData["components"]);
        }
        $info .= "\n}";

        //类文件路径
        $classPath = self::$path.'/'.$className.'.php';
        //不存在则创建文件
        if(!file_exists($classPath)){
            //创建类文件
            $res = file_put_contents($classPath, $info);
            if($res){
                $this->output .= $className.".php 类创建成功\n";
            }else{
                $this->output .= $className.".php 类创建失败\n";
            }
        }else{
            exit(setJsonStr($className.".php 类文件已存在"));
        }
    }
    /*
     * 生成列表方法
     * @param string $lowerClassName 首字母小写类名
     */
    protected function createList(string $lowerClassName): string {
        $className = self::$className; //完整类名
        $chineseClassName = self::$chineseClassName; //类的中文别名
        $url = $className."/".$lowerClassName;     //控制器、方法地址
        //创建html
        $info = "    /**\n";
        $info .= "     * {$chineseClassName}列表\n";
        $info .= "     */";
        $info .= "\n    public function {$lowerClassName}List(){";
        $info .= "\n        $"."userData = Session::get('userData');";
        $info .= "\n        $"."map = [];";
        $info .= "\n        //查询数据";
        $info .= "\n        $"."info = {$className}Model::get{$className}Page($"."map);";
        $info .= "\n        //权限验证";
        $info .= "\n        $"."rules = ['{$url}'".self::OPERATE_ADD."', '{$url}".self::OPERATE_EDIT."', '{$url}Del', '{$url}DelAll', '{$url}Export'];";
        $info .= "\n        $"."check = AuthGroup::checkMethodArray($"."userData, $"."rules);\n";
        $info .= "\n        View::assign('info',$"."info);";
        $info .= "\n        View::assign('check',$"."check);";
        $info .= "\n        return View::fetch('{$lowerClassName}List');";
        $info .= "\n    }\n";
        //列表方法插入权限表
        $pid = AuthRule::authRuleAdd("{$url}", "{$chineseClassName}管理", self::$authPid);
        self::$authPid = AuthRule::authRuleAdd("{$url}List", "{$chineseClassName}列表", $pid);
        return $info;
    }
    /*
     * 生成新增/编辑统一入口
     * @param string $lowerClassName 首字母小写类名
     * @param string $fieldId 表的id字段名
     */
    protected function createOperate(string $lowerClassName, string $fieldId): string {
        $className = self::$className; //完整类名
        $chineseClassName = self::$chineseClassName; //类的中文别名
        $url = $className."/"."$lowerClassName";     //控制器、方法地址
        $info = "    /**\n";
        $info .= "     * {$chineseClassName}新增/编辑统一入口\n";
        $info .= "     */";
        $info .= "\n    public function {$lowerClassName}Operate(string $"."operate){\n";
        $info .= "        if($"."operate == ".REQUEST_ADD."){          /**新增*/\n";
        $info .= "            if(Request::isPost()) return $"."this->{$lowerClassName}Add();\n";
        $info .= "        }elseif($"."operate == ".REQUEST_EDIT."){    /**编辑*/\n";
        $info .= "            if(Request::isPost()) return $"."this->{$lowerClassName}Edit();\n";
        $info .= "        }else{\n";
        $info .= "            return alertDemo(\"请求错误\");\n";
        $info .= "        }\n";
        $info .= "        $"."id = input('id');\n";
        $info .= "        $"."info = {$className}Model::get{$className}Detail(['$fieldId'=>$"."id]);\n";
        $info .= "        View::assign('info', $"."info);\n";
        $info .= "        return View::fetch('{$lowerClassName}Operate');\n";
        $info .= "\n    }\n";
        //新增和编辑方法插入权限表
        AuthRule::authRuleAdd("{$url}Operate", "{$chineseClassName}新增/编辑统一入口", self::$authPid);
        return $info;
    }
    /*
     * 生成新增方法
     * @param string $lowerClassName 首字母小写类名
     */
    protected function createAdd(string $lowerClassName): string {
        $className = self::$className; //完整类名
        $chineseClassName = self::$chineseClassName; //类的中文别名
        $url = $className."/"."$lowerClassName";     //控制器、方法地址
        $info = "    /**\n";
        $info .= "     * {$chineseClassName}新增\n";
        $info .= "     */";
        $info .= "\n    protected function {$lowerClassName}Add(){\n";
        $info .= "          //接收数据\n";
        $info .= "          $"."map = input();\n";
        $info .= "          //空值验证\n";
        $info .= "          checkField($"."map, ['id']);\n";
        $info .= "          //插入数据\n";
        $info .= "          $"."info = {$className}Model::create($"."map);\n";
        $info .= "          if($"."info){\n";
        $info .= "              Log::logAdd(Session::get('userData.ad_id'), '新增{$chineseClassName}'); //写入日志\n";
        $info .= "              $"."data = ['info'=>'新增成功','status'=>1];\n";
        $info .= "          }else{\n";
        $info .= "              $"."data = ['info'=>'新增失败','status'=>0];\n";
        $info .= "          }\n";
        $info .= "          return json($"."data);\n";
        $info .= "\n    }\n";
        //新增方法插入权限表
        AuthRule::authRuleAdd("{$url}Operate/operate/add", "{$chineseClassName}新增", self::$authPid);
        return $info;
    }
    /*
     * 生成编辑方法
     * @param string $lowerClassName 首字母小写类名
     * @param string $fieldId 表的id字段名
     */
    protected function createEdit(string $lowerClassName, string $fieldId): string {
        $className = self::$className; //完整类名
        $chineseClassName = self::$chineseClassName; //类的中文别名
        $url = $className."/"."$lowerClassName";     //控制器、方法地址
        $info = "    /**\n";
        $info .= "     * {$chineseClassName}编辑\n";
        $info .= "     */";
        $info .= "\n    public function {$lowerClassName}Edit(){\n";
        $info .= "        $"."id = input('id');\n";
        $info .= "        if(Request::isPost()){\n";
        $info .= "            //接收数据\n";
        $info .= "            $"."map = input();\n";
        $info .= "            //空值验证\n";
        $info .= "            checkField($"."map);\n";
        $info .= "            //插入数据\n";
        $info .= "            $"."info = {$className}Model::update($"."map, ['$fieldId'=>$"."id]);\n";
        $info .= "            if($"."info){\n";
        $info .= "                Log::logAdd(Session::get('userData.ad_id'), '编辑{$chineseClassName}');//写入日志\n";
        $info .= "                $"."data = ['info'=>'编辑成功','status'=>1];\n";
        $info .= "            }else{\n";
        $info .= "                $"."data = ['info'=>'编辑无变化','status'=>0];\n";
        $info .= "            }\n";
        $info .= "            return json($"."data);\n";
        $info .= "        }";
        $info .= "\n        $"."info = {$className}Model::get{$className}Detail(['$fieldId'=>$"."id]);\n";
        $info .= "\n        View::assign('info', $"."info);";
        $info .= "\n        return View::fetch('{$lowerClassName}Edit');";
        $info .= "\n    }\n";
        //编辑方法插入权限表
        AuthRule::authRuleAdd("{$url}Operate/operate/edit", "{$chineseClassName}编辑", self::$authPid);
        return $info;
    }
    /*
     * 生成删除方法
     * @param string $lowerClassName 首字母小写类名
     * @param string $fieldId 表的id字段名
     */
    protected function createDel(string $lowerClassName, string $fieldId): string {
        $className = self::$className; //完整类名
        $chineseClassName = self::$chineseClassName; //类的中文别名
        $url = $className."/"."$lowerClassName";     //控制器、方法地址
        $info = "    /**\n";
        $info .= "     * {$chineseClassName}删除\n";
        $info .= "     */";
        $info .= "\n    public function {$lowerClassName}Del(){\n";
        $info .= "        if(Request::isDelete()){\n";
        $info .= "            $"."id = input('id');\n";
        $info .= "            //删除数据\n";
        $info .= "            $"."info = {$className}Model::where('$fieldId',$"."id)->delete();\n";
        $info .= "            if($"."info){\n";
        $info .= "                Log::logAdd(Session::get('userData.ad_id'), '删除{$chineseClassName}');//写入日志\n";
        $info .= "                $"."data = ['info'=>'删除成功','status'=>1];\n";
        $info .= "            }else{\n";
        $info .= "                $"."data = ['info'=>'删除失败','status'=>0];\n";
        $info .= "            }\n";
        $info .= "        }else{\n";
        $info .= "            $"."data = ['info'=>'请求错误','status'=>0];\n";
        $info .= "        }";
        $info .= "\n        return json($"."data);";
        $info .= "\n    }\n";
        //删除方法插入权限表
        AuthRule::authRuleAdd("{$url}Del", "{$chineseClassName}删除", self::$authPid);
        return $info;
    }
    /*
     * 生成批量删除方法
     * @param string $lowerClassName 首字母小写类名
     * @param string $fieldId 表的id字段名
     */
    protected function createDelAll(string $lowerClassName, string $fieldId): string {
        $className = self::$className; //完整类名
        $chineseClassName = self::$chineseClassName; //类的中文别名
        $url = $className."/"."$lowerClassName";     //控制器、方法地址
        $info = "    /**\n";
        $info .= "     * {$chineseClassName}批量删除\n";
        $info .= "     */";
        $info .= "\n    public function {$lowerClassName}DelAll(){\n";
        $info .= "        if(Request::isDelete()){\n";
        $info .= "            $"."ids = input('ids');\n";
        $info .= "            //删除数据\n";
        $info .= "            $"."info = {$className}Model::where('$fieldId', 'in', $"."ids)->delete();\n";
        $info .= "            if($"."info){\n";
        $info .= "                Log::logAdd(Session::get('userData.ad_id'), '批量删除{$chineseClassName}'); //写入日志\n";
        $info .= "\n              $"."data = ['info'=>'删除成功','status'=>1];\n";
        $info .= "            }else{\n";
        $info .= "                $"."data = ['info'=>'删除失败','status'=>0];\n";
        $info .= "            }\n";
        $info .= "        }else{\n";
        $info .= "            $"."data = ['info'=>'请求错误','status'=>0];\n";
        $info .= "        }";
        $info .= "\n        return json($"."data);";
        $info .= "\n    }\n";
        //批量删除方法插入权限表
        AuthRule::authRuleAdd("{$url}DelAll", "{$chineseClassName}批量删除", self::$authPid);
        return $info;
    }
    /*
     * 生成导出方法
     * @param string $lowerClassName 首字母小写类名
     * @param array $fields 字段信息
     * @param array $listFiled 需要的字段数据
     */
    protected function createExport(string $lowerClassName, array $fields, array $listFiled): string {
        $className = self::$className; //完整类名
        $chineseClassName = self::$chineseClassName; //类的中文别名
        $url = $className."/"."$lowerClassName";     //控制器、方法地址
        $data = ""; //备注
        $field = ""; //字段名
        //返回所有key值
        $listFiledArray = array_keys($listFiled);
        //数组组合成充填
        foreach ($fields as $value) {
            if(in_array($value["Field"], $listFiledArray)){
                $data .= "'".$value['Comment']."',";
                $field .= "'".$value['Field']."',";
            }
        }
        //去掉最右侧，号
        $data = rtrim($data, ",");
        $field = rtrim($field, ",");

        $info = "    /**\n";
        $info .= "     * {$chineseClassName}导出\n";
        $info .= "     */";
        $info .= "\n    public function {$lowerClassName}Export(){";
        $info .= "\n        $"."map = [];";
        $info .= "\n        $"."info = {$className}Model::get{$className}List($"."map);\n";
        $info .= "\n        $"."data = [".$data."];";
        $info .= "\n        $"."field = [".$field."];\n";
        $info .= "\n        $"."export = exportData($"."data, $"."info->toArray(), $"."field);";
        $info .= "\n        return json($"."export);";
        $info .= "\n    }\n";
        //导出方法插入权限表
        AuthRule::authRuleAdd("{$url}Export", "{$chineseClassName}批量导出", self::$authPid);
        return $info;
    }
//=================================================【创建Html】==========================================================
    /*
     * 生成HTML文件
     * @param array $fields 表字段信息
     * @param array $createData 创建html需要的字段数据
     */
    protected function createHtml(array $fields, array $createData){
        //显示字段
        $showField = $createData["components"];
        //创建列表html文件
        if(!empty($createData["features"]["list"])) {
            $this->createListHtml(self::$lowerClassName, $fields, $showField, $createData["features"]);
        }
        //创建新增/编辑统一html文件
        if(!empty($createData["features"][REQUEST_ADD]) || !empty($createData["features"][REQUEST_EDIT])) {
            $this->createOperateHtml(self::$lowerClassName, $fields, $showField);
        }
        //创建新增html文件
//        if(!empty($createData["features"][REQUEST_ADD])) {
//            $this->createAddHtml(self::$lowerClassName, $fields, $showField);
//        }
        //创建编辑html文件
//        if(!empty($createData["features"][REQUEST_EDIT])) {
//            $this->createEditHtml(self::$lowerClassName, $fields, $showField);
//        }
    }
    /*
     * 创建列表html文件
     * @param string $lowerClassName 首字母小写类名
     * @param string $fields 表字段信息
     * @param array $listFiled 列表需要创建的字段
     * @param array $features 创建需要的功能
     */
    protected function createListHtml(string $lowerClassName, array $fields, array $listFiled, array $features){
        //完整类名
        $className = self::$className;
        //列表模板路径
        $listTplPath = self::$path.'/../../common/template/list.html';
        //获取模板信息
        $info = file_get_contents($listTplPath);
        //表格 thead
        $thead = "";
        //id 字段名
        $fieldId = self::$primayKey["Field"];
        //所有字段名
        $field = "";
        //数组组合成充填
        foreach ($fields as $value) {
            $key = $value["Field"];
            if(!empty($listFiled[$key])){
                $thead .=  "                                <th>{$value['Comment']}</th>\r\n";
                $field .=  '                                    <td>{$'.'vo.'.$value["Field"].'}</td>'."\r\n";
            }
        }
        $thead = rtrim($thead, "\r\n");
        //新增
        $operating = '';
        if(!empty($features[REQUEST_ADD])) {
            $operating .= $this->createButton(REQUEST_ADD, $className, $lowerClassName);
        }
        //导出
        if(!empty($features[REQUEST_EXPORT])) {
            $operating .= $this->createButton(REQUEST_EXPORT, $className, $lowerClassName);
        }
        //批量删除
        if(!empty($features[REQUEST_DEL_ALL])) {
            $operating .= $this->createButton(REQUEST_DEL_ALL, $className, $lowerClassName);
        }
        //编辑
        $field .= "                                    <td>\n";
        if(!empty($features[REQUEST_EDIT])) {
            $field .= $this->createButton(REQUEST_EDIT, $className, $lowerClassName, $fieldId);
        }
        //删除
        if(!empty($features[REQUEST_DEL])) {
            $field .= $this->createButton(REQUEST_DEL, $className, $lowerClassName, $fieldId);
        }
        $field .= "                                    </td>";

        //要填充的变量
        $info = vsprintf($info, [
            "{:url('{$className}/{$lowerClassName}List')}",
            $operating,
            $thead,
            '{$'.'vo.'.$fieldId.'}',
            $field,
            "{:url('{$className}/{$lowerClassName}DelAll')}",
            "{:url('{$className}/{$lowerClassName}Del')}",
            "{:url('{$className}/{$lowerClassName}Export')}"
        ]);
        //要创建的目录
        $creatPath = self::$path.'/../view/'.self::$prefixTableName;
        //不存在则创建文件夹
        if(!is_dir($creatPath)) mkdir($creatPath ,0755, true);
        //创建html文件的路径
        $listPath = $creatPath.'/'.$lowerClassName.'List.html';
        //创建html文件
        $res = file_put_contents($listPath, $info);
        if($res){
            $this->output .= $lowerClassName."List.html创建成功\n";
        }else{
            $this->output .= $lowerClassName."List.html创建失败\n";
        }
    }
    /*
     * 创建新增/编辑统一Html文件
     * @param string $lowerClassName 首字母小写类名
     * @param array $fields 表字段信息
     * @param array $addFiled 创建需要的字段
     */
    protected function createOperateHtml(string $lowerClassName, array $fields, array $addFiled){
        //完整类名
        $className = self::$className;
        //模板路径
        $tplPath = self::$path.'/../../common/template/operate.html';
        //获取模板信息
        $info = file_get_contents($tplPath);
        //要填充的html数据
        $res = $this->createInput($addFiled, $fields, 1);
        //要填充的变量
        $info = vsprintf($info, ['{$'.'info.'.self::$primayKey["Field"].'}', $res, "{:url('{$className}/{$lowerClassName}Operate')}"]);
        //要创建的目录
        $creatPath = self::$path.'/../view/'.self::$prefixTableName;
        //不存在则创建文件夹
        if(!is_dir($creatPath)) mkdir($creatPath ,0755, true);
        //创建html文件的路径
        $listPath = $creatPath.'/'.$lowerClassName.'Operate.html';
        //创建html文件
        $res = file_put_contents($listPath, $info);
        if($res){
            $this->output .= $lowerClassName."Operate.html创建成功\n";
        }else{
            $this->output .= $lowerClassName."Operate.html创建失败\n";
        }
    }
    /*
     * 创建新增Html文件
     * @param string $lowerClassName 首字母小写类名
     * @param array $fields 表字段信息
     * @param array $addFiled 创建需要的字段
     */
    protected function createAddHtml(string $lowerClassName, array $fields, array $addFiled){
        //完整类名
        $className = self::$className;
        //模板路径
        $tplPath = self::$path.'/../../common/template/add.html';
        //获取模板信息
        $info = file_get_contents($tplPath);
        //要填充的html数据
        $res = $this->createInput($addFiled, $fields);
        //要填充的变量
        $info = vsprintf($info, [$res, "{:url('{$className}/{$lowerClassName}Add')}"]);
        //要创建的目录
        $creatPath = self::$path.'/../view/'.self::$prefixTableName;
        //不存在则创建文件夹
        if(!is_dir($creatPath)) mkdir($creatPath ,0755, true);
        //创建html文件的路径
        $listPath = $creatPath.'/'.$lowerClassName.'Add.html';
        //创建html文件
        $res = file_put_contents($listPath, $info);
        if($res){
            $this->output .= $lowerClassName."Add.html创建成功\n";
        }else{
            $this->output .= $lowerClassName."Add.html创建失败\n";
        }
    }
    /*
     * 创建编辑Html文件
     * @param string $lowerClassName 首字母小写类名
     * @param array $fields 表字段信息
     * @param array $editFiled 创建需要的字段
     */
    protected function createEditHtml(string $lowerClassName, array $fields, array $editFiled){
        //完整类名
        $className = self::$className;
        //模板路径
        $tplPath = self::$path.'/../../common/template/edit.html';
        //获取模板信息
        $info = file_get_contents($tplPath);
        //要填充的html数据
        $res = $this->createInput($editFiled, $fields, 1);
        //要填充的变量
        $info = vsprintf($info, ['{$'.'info.'.self::$primayKey["Field"].'}', $res, "{:url('{$className}/{$lowerClassName}Edit')}"]);
        //要创建的目录
        $creatPath = self::$path.'/../view/'.self::$prefixTableName;
        //不存在则创建文件夹
        if(!is_dir($creatPath)) mkdir($creatPath ,0755, true);
        //创建html文件的路径
        $listPath = $creatPath.'/'.$lowerClassName.'Edit.html';
        //创建html文件
        $res = file_put_contents($listPath, $info);
        if($res){
            $this->output .= $lowerClassName."Edit.html创建成功\n";
        }else{
            $this->output .= $lowerClassName."Edit.html创建失败\n";
        }
    }
    /**
     * 需要创建的操作按钮
     * @param string $type 操作类型
     * @param string $className 类名
     * @param string $lowerClassName 小驼峰类名
     * @param string $fieldId id字段名
     * @return string
     */
    protected function createButton(string $type, string $className, string $lowerClassName, string $fieldId="id"){
        $button = "";
        switch ($type){
            case REQUEST_ADD:
                $button = ' {eq name="check.'.$className.$lowerClassName.self::OPERATE_ADD_ADDRESS.'" value="1"}
                        <button class="layui-btn" onclick="common.openWindow(\'新增\',\'{:url(\''.$className.'/'.$lowerClassName.'Operate\', [\'operate\'=>\''.REQUEST_ADD.'\'])}\',\'500\')" >
                            <i class="layui-icon">&#xe654;</i>新增
                        </button>
                     {/eq}'."\r\n";;
                break;
            case REQUEST_EXPORT:
                $button = '                     {eq name="check.'.$className.$lowerClassName.'Export" value="1"}
                        <button class="layui-btn" onclick="dataExport()">
                            <i class="layui-icon">&#xe67d;</i>数据导出
                        </button>
                     {/eq}'."\r\n";
                break;
            case REQUEST_DEL_ALL:
                $button = '                     {eq name="check.'.$className.$lowerClassName.'DelAll" value="1"}
                        <button class="layui-btn layui-btn-danger" onclick="dataDelAll()">
                            <i class="layui-icon">&#xe640;</i>批量删除
                        </button>
                     {/eq}';
                break;
            case REQUEST_EDIT:
                $button = '                                        {eq name="check.'.$className.$lowerClassName.self::OPERATE_EDIT_ADDRESS.'" value="1"}
                                            <a href="javascript:;" onclick="common.openWindow(\'编辑\',\'{:url(\''.$className.'/'.$lowerClassName.'Operate\',[\'operate\'=>\''.REQUEST_EDIT.'\', \'id\'=>$'.'vo.'.$fieldId.'])}\',\'500\')" >
                                                <i class="layui-icon">&#xe642;</i>编辑
                                            </a>
                                        {/eq}'."\r\n";
                break;
            case REQUEST_DEL:
                $button = '                                        {eq name="check.'.$className.$lowerClassName.'Del" value="1"}
                                            <a href="javascript:;" onclick="dataDel(this,\'{$'.'vo.'.$fieldId.'}\')" >
                                                <i class="layui-icon">&#xe640;</i>删除
                                            </a>
                                        {/eq}'."\r\n";
                break;
        }
        return $button;
    }
    /**
     * 创建需要的Input输入框
     * @param array $createFiled 要创建的字段名
     * @param array $fields 表字段信息
     * @param int $filling 是否填充变量：1是0否
     * @return string
     */
    protected function createInput(array $createFiled, array $fields, int $filling=0){
        $res = "";
        //数组组合成充填
        foreach ($fields as $value) {
            //选出需要填充的字段
            $key = $value['Field'];
            if(!empty($createFiled[$key])){
                //获取要填充的input框类型
                $res .= $this->getTypeInput($createFiled[$key], $value['Comment'], $value['Field'], $filling);
            }
        }
        return $res;
    }
    /**
     * 返回对应类型的输入框
     * @param int $type 1文本，2下拉，3复选，4单选，5文本域
     * @param string $comment 字段备注
     * @param string $field 字段名
     * @param int $filling 是否填充变量：1是0否
     * @return string
     */
    protected function getTypeInput(int $type, string $comment, string $field, int $filling=0){
        $res = "";
        //填充变量
        $filling == 0 ? $variable = "" : $variable = '{$'.'info.'.$field.'}';
        switch ($type){
            case self::FORM_TEXT:
                $res = "<div class=\"layui-form-item\">
                        <label for=\"title\" class=\"layui-form-label\">
                            <span class=\"x-red\">*</span>{$comment}
                        </label>
                        <div class=\"layui-input-inline\">
                            <input type=\"text\" id=\"{$field}\" name=\"{$field}\" value=\"{$variable}\" lay-verify=\"required\" autocomplete=\"off\" class=\"layui-input\">
                        </div>
                    </div>\r\n                    ";
                break;
            case self::FORM_SELECT:
                $res = "<div class=\"layui-form-item\">
                        <label for=\"title\" class=\"layui-form-label\">
                            <span class=\"x-red\">*</span>{$comment}
                        </label>
                        <div class=\"layui-input-inline\">
                            <select name=\"{$field}\" id=\"{$field}\">
                                <option value=\"1\" selected >启用</option>
                                <option value=\"0\" >禁用</option>
                            </select>
                        </div>
                    </div>\r\n                    ";
                break;
            case self::FORM_CHECKBOX:
                $res = "<div class=\"layui-form-item\">
                        <label for=\"title\" class=\"layui-form-label\">
                            <span class=\"x-red\">*</span>{$comment}
                        </label>
                        <div class=\"layui-input-inline\">
                            <input type=\"checkbox\" name=\"{$field}[]\" title=\"{$comment}1\" lay-skin=\"primary\" checked>
                            <input type=\"checkbox\" name=\"{$field}[]\" title=\"{$comment}2\" lay-skin=\"primary\">
                            <input type=\"checkbox\" name=\"{$field}[]\" title=\"{$comment}3\" lay-skin=\"primary\">
                        </div>
                    </div>\r\n                    ";
                break;
            case self::FORM_RADIO:
                $res = "<div class=\"layui-form-item\">
                        <label for=\"title\" class=\"layui-form-label\">
                            <span class=\"x-red\">*</span>{$comment}
                        </label>
                        <div class=\"layui-input-inline\">
                            <input type=\"radio\" name=\"{$field}\" value=\"{$comment}\" title=\"{$comment}1\" checked>
                            <input type=\"radio\" name=\"{$field}\" value=\"{$comment}\" title=\"{$comment}2\">
                        </div>
                    </div>\r\n                    ";
                break;
            case self::FORM_TEXTAREA:
                $res = "<div class=\"layui-form-item\">
                        <label for=\"title\" class=\"layui-form-label\">
                            <span class=\"x-red\">*</span>{$comment}
                        </label>
                        <div class=\"layui-input-inline\">
                            <textarea name=\"{$field}\" placeholder=\"请输入内容\" class=\"layui-textarea\">{$variable}</textarea>
                        </div>
                    </div>\r\n                    ";
                break;
        }
        return $res;
    }
}